import { get } from '../api/ajax'
import API from '@/api/apis'

// 必须继承才能使用
class BaseModel {

  public _id: string = ''

  // 获取json对象
  public static getJson(obj: BaseModel, keys: string[], json = {}) {
    return obj.getJson(keys, json)
  }

  // 根据数据设置对象并获取
  public static creatModelWithJson(json: object) {
    const model = new this()
    model.setDataWithJson(json)
    return model
  }

  // 根据json数组获取数组对象
  public static getModelsWithArr(dataArr: object[]) {
    if (dataArr instanceof Array) {
      return dataArr.map((item) => {
        return this.creatModelWithJson(item)
      })
    } else {
      return []
    }
  }

  public static loadModels(url: string, page: number, otherData = {}) {
    return new Promise((resolve, reject) => {
      get(url, {
        page,
        ...otherData
      }).then((data: any) => {
        resolve(this.getModelsWithArr(data))
      }).catch((err) => {
        reject(err)
      })
    })
  }

  // 加载所有banner数据
  public static loadAllModels(url: string) {
    return new Promise<BaseModel[]>((resolve, reject) => {
      get(url).then((dataArr: any) => {
        resolve(this.getModelsWithArr(dataArr))
      }).catch((err) => {
        reject(err)
      })
    })
  }

  // 设置数据
  public setDataWithJson(json: {}) {
    // 不适用 Object.assign 就是为了保持类的清洁，清除不必要的字段
    for (const k in json) {
      if ((this as any)[k] !== undefined) {
        (this as any)[k] = (json as any)[k]
      }
    }
    // Object.assign(this, json)
  }

  // 根据传入的数组获取模型
  public getJson(keys: string[], json = {}) {
    if (keys instanceof Array) {
      keys.forEach((key) => {
        (json as any)[key] = (this as any)[key]
      })
    }
    return json
  }
}

export default BaseModel
